﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using HJ212_Common;
using HJT212_Protocol_DAL.DAO;
using HJT212_Protocol_DAL.Model;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;
using SailHero.Soft.ESB.Threading;
namespace HJT212_Protocol_Server
{
    public class CommunicationServer
    {
        #region 字段属性

        public HostProtocolServer HostSrv { get; set; }

        public ProtocolServer ClntSrv { get; set; }

        private log4net.ILog log = log4net.LogManager.GetLogger(
            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public delegate void showOnlineClients(List<ClientModel> LstClts);

        public showOnlineClients showOnline;

        public delegate void showHostOnlineClients(List<HostClientModel> LstHClients);

        public showHostOnlineClients showHostOnline;


        public delegate void showHostOnlineEndPointsEventHandler(List<string> LstHEndPoints);

        public showHostOnlineEndPointsEventHandler showHostOnlineEndPoints;

        public delegate void showMsgEventHandler(string msg);

        public showMsgEventHandler showTraceMsg;
        public showMsgEventHandler showHostTraceMsg;


        public List<ClientModel> LstClients { get; set; }

        public List<HostClientModel> LstHostClients { get; set; }

        /// <summary>
        /// This timer
        /// </summary>
        private readonly System.Timers.Timer _ClearTimer;


        /// <summary>
        /// 发送数据的超时时间（只是同步发送）
        /// </summary>
        public int SendTimeOut { get; set; }

        /// <summary>
        /// 超时重发次数
        /// </summary>
        public int SendTimes
        {
            get;
            set;
        }


        /// <summary>
        /// 超时登录时间
        /// </summary>
        public int LoginTimeOut
        {
            get;
            set;
        }



        /// <summary>
        /// 服务是否正在运行状态
        /// </summary>
        public bool IsRuning
        {

            get
            {
                string SrvPort = ConfigOprater.GetNodeValue("SrvPort");
                string HostSrvPort = ConfigOprater.GetNodeValue("HostSrvPort");
                OperateIPEndPoint opt = new OperateIPEndPoint();
                if (opt.IsUsedIPEndPoint((Convert.ToInt32(SrvPort))) || opt.IsUsedIPEndPoint((Convert.ToInt32(HostSrvPort))))
                {
                    return true;
                }

                if (HostSrv == null || ClntSrv == null)
                {
                    return false;
                }
                else
                {
                    return HostSrv.IsRuning && ClntSrv.IsRuning;
                }
            }
        }


        public int HostClientCount
        {
            get
            {
                if (HostSrv == null) { return 0; }
                return this.HostSrv.server.Clients.Count;
            }
        }

        public int ClientCount
        {

            get
            {
                if (ClntSrv == null) { return 0; }
                return this.ClntSrv.server.Clients.Count;
            }
        }



        #endregion

        public CommunicationServer()
        {
            _ClearTimer = new System.Timers.Timer(2 * 60 * 60 * 1000);//2天自动清理
            _ClearTimer.Elapsed += _ClearTimer_Elapsed;
        }


        #region 方法
        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            try
            {
                HostSrv = new HostProtocolServer();
                ClntSrv = new ProtocolServer();
                HostSrv.Init(this);
                ClntSrv.Init(this);
                ClntSrv.server.LoginTimeOut = LoginTimeOut;

            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }



        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            try
            {
                if (HostSrv != null && ClntSrv != null)
                {
                    _ClearTimer.Stop();
                    HostSrv.Stop();
                    ClntSrv.Stop();
                }
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }
        /// <summary>
        /// 停止
        /// </summary>
        public void Start()
        {
            try
            {
                if (HostSrv != null && ClntSrv != null)
                {
                    HostSrv.Start();
                    ClntSrv.Start();
                    _ClearTimer.Start();
                }
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }
        public void UpdateOffLineAll()
        {
            try
            {
                foreach (ClientModel mdl in LstClients.Where(itm => !string.IsNullOrEmpty(itm.MN)))
                {
                    ClientDao clntDao = new ClientDao();
                    clntDao.UpdateOnlineState(mdl.MN, 0);
                }

                foreach (HostClientModel mdl in LstHostClients)
                {
                    HostClientDao HclntDao = new HostClientDao();
                    HclntDao.UpdateOnlineState(mdl.MN, 0);
                }
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        public CMD_SendModel ConvertToMdlFromMsg(TextMessage mesg)
        {
            if (mesg == null) return null;
            try
            {
                CMD_SendModel cmdM = new CMD_SendModel()
                {
                    QN = mesg.QN,
                    MN = mesg.MN,
                    PW = mesg.PW,
                    CN = mesg.CN,
                    CP = mesg.CP,
                    ST = mesg.ST
                };
                return cmdM;

            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }

            return null;
        }


        public CMD_ReturnModel ConvertToRMdlFromMsg(TextMessage mesg)
        {
            if (mesg == null) return null;
            try
            {
                string content = mesg.Text.ToUpper().Replace(" ", "").Replace("　", "");
                string ExeRtn0 = "", QNRtn0 = "";
                int k = content.IndexOf("EXERTN=");
                if (k >= 0)
                {
                    ExeRtn0 = content.Substring(k + 7, 3);//ExeRtn的宽度为N3
                }
                int j = content.IndexOf("QNRTN=");
                if (j >= 0)
                {
                    QNRtn0 = content.Substring(j + 6, 3);//QNRtn的宽度为N3
                }
                CMD_ReturnModel cmdM = new CMD_ReturnModel()
                {
                    QN = mesg.QN,
                    MN = mesg.MN,
                    PW = mesg.PW,
                    CN = mesg.CN,
                    CP = mesg.CP,
                    ST = mesg.ST,
                    ExeRtn = handleWidthNstr(ExeRtn0),
                    QNRtn = handleWidthNstr(QNRtn0),
                    isDisp = 1
                };
                return cmdM;

            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }

            return null;
        }




        /// <summary>
        /// 处理指定宽度的数字字串
        /// </summary>
        private string handleWidthNstr(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            string strs = str;
            int dd = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (isNumberic(strs, out dd))
                {
                    break;
                }
                else
                {
                    strs = strs.Substring(0, strs.Length - 1);
                }
            }
            return dd.ToString();
        }

        private bool isNumberic(string message, out int result)
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            result = -1;
            if (rex.IsMatch(message))
            {
                result = int.Parse(message);
                return true;
            }
            else
                return false;
        }

        private void _ClearTimer_Elapsed(object sender, EventArgs e)
        {
            try
            {

                MsgCacheDao msgcacheDao = new MsgCacheDao();
                msgcacheDao.ClearCache();
                this.HostSrv.CleanNoUsedClient(2);
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }





        #endregion



    }
}
